package cn.xaut.查找表;

import java.util.*;

public class demo15 {

    public List<List<Integer>> threeSum2(int[] nums) {
        
        List<List<Integer>> res = new ArrayList<>();

        Arrays.sort(nums);

        for (int i = 0; i < nums.length; i++) {

            if (nums[i] > 0)
                break;
            
            // 去掉重复情况
            if (i > 0 && nums[i - 1] == nums[i])
                continue;

            int target = -nums[i];
            
            // 对撞指针找两数之和为 target 的数
            int l = i + 1, r = nums.length - 1;
            while (l < r) {
                int sum = nums[l] + nums[r];
                if (sum == target) {
                    res.add(new ArrayList<>(Arrays.asList(nums[i], nums[l], nums[r])));
                    l ++;
                    r --;
                    while (l < r && nums[l] == nums[l - 1])
                        l ++;
                    while (l < r && nums[r] == nums[r + 1])
                        r --;
                } else if (sum > target)
                    r--;
                else    // sum < target
                    l++;
            }
        }
        
        return res;
    }


    // [0,0,0,0] 出错
    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> res = new ArrayList<>();

        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length; i++) {
            
            // 去掉重复情况
            if (i > 0 && nums[i - 1] == nums[i])
                continue;
            
            int target = -nums[i];
            Set<Integer> set = new HashSet<>();
            for (int j = i + 1; j < nums.length; j++) {
                if (set.contains(target - nums[j])) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(target - nums[j]);
                    res.add(list);
                } else            
                    set.add(nums[j]);
            }
        }
        
        return res;
    }

    public static void main(String[] args) {

        List<List<Integer>> res = new demo15().threeSum2(new int[]{-1, 0, 1, 2, -1, -4});
        for (List<Integer> list : res)
            System.out.println(list);   // [[-1,-1,2],[-1,0,1]]
    }
}
